package com.example.zn.controller;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zn.dto.Result;
import com.example.zn.entity.User;
import com.example.zn.entity.User;
import com.example.zn.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Objects;

@CrossOrigin
@Tag(name="用户接口",description = "对于用户相关功能接口，如：注册，登录，信息更新，查看，删除等操作")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Operation(summary = "用户登录", description = "需要提供账号和登录密码")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "password", description = "密码")
    })

    @GetMapping("/user/login")
    public Result login(@Parameter(description = "用户ser对象") @RequestBody User user) {
        return userService.login(user);
    }


    @Operation(summary = "用户注册")
    @PostMapping("/user/reg")
    public Result reg(@Parameter(description = "用户ser对象") @RequestBody User user) {
        return userService.reg(user);
    }


    /**
     * 分页查询
     *
     * @param page  当前显示的页码数
     * @param limit 每页数据条目数
     * @return
     */
    @Operation(summary = "分页查询用户", description = "显示所有用户信息，其中密码随机盐做脱敏处理")
    @Parameters({  //参数集
            @Parameter(name = "page", description = "当前页", required = true),
            @Parameter(name = "limit", description = "每页数据条目数", required = true)
    })
    @GetMapping("/user/list")
    public Result list(@RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "5") Integer limit ) {
        //执行分页查询
        List<User> list = userService.list(new Page<>(page, limit));
        if (list.isEmpty()) {
            return Result.fail().setMsg("无记录");
        }
        list.forEach(user -> {
            //取出密码、盐脱敏后重新填充到密码属性中
            user.setPassword(DesensitizedUtil.password(user.getPassword()));
            user.setSalt(DesensitizedUtil.password(user.getSalt()));
        });
        //查询总记录数
        long count = userService.count();
        return Result.ok().setMsg("查询成功").setData(list).setCount((int) count);
    }

    //    用户信息修改
    @Operation(summary = "用户信息更新", description = "根据id修改密码或状态，id必须提供")
    @PostMapping("/user/update")
    public Result modify(@Parameter(description = "用户ser对象") @RequestBody User user) {
        //判断是否需要修改密码
        if (Objects.nonNull(user.getPassword())) {
            //生成盐
            String salt = RandomUtil.randomString(6);
            //使用盐和输入密码加密
            String pwd = SecureUtil.md5(user.getPassword() + salt);
            //将新密码和随机盐添加到对象中
            user.setPassword(pwd);
            user.setSalt(salt);
        }
        //执行修改（根据id修改）
        if (userService.updateById(user)) {
            return Result.ok().setMsg("修改成功").setData(user);
        }
        return Result.fail().setMsg("更新失败");
    }

    @Operation(summary = "查询所有用户ser信息",description = "需要提供")
    @GetMapping("/user/listAll")
    public Result selectAll(){
        List<User> list = userService.list();
        if (list.isEmpty()){
            return Result.fail().setMsg("无记录");
        }
        list.forEach(user -> {
//            取出密码，将盐脱敏后重新填充到密码中
            user.setPassword(DesensitizedUtil.password(user.getPassword()));
            user.setSalt(DesensitizedUtil.password(user.getSalt()));
        });
        return Result.ok().setMsg("查询成功").setData(list);
    }

    
    /**
     * 根据id删除用户ser(物理删除：谨慎操作)
     *
     * @param id
     * @return
     */
    @Operation(summary = "根据id删除用户ser",description = "需要提供用户ser的id")
    @DeleteMapping("/user/{id}")
    public Result delById(@Parameter(description = "用户serid", required = true) @PathVariable("id") Integer id){
        User user = userService.getById(id);
        if (Objects.isNull(user)){
            return Result.fail().setMsg("该用户ser不存在！");
        }
        if (userService.removeById(id)){
            return Result.ok().setMsg("删除成功").setData(user);
        }
        return Result.fail().setMsg("删除失败");
    }

}

